<template>
	<view class="content">
		<scroll-view scroll-y class="message-list" :scroll-into-view="`msg-${messages.list.length - 1}`"
			scroll-with-animation>
			<view v-for="(msg, index) in messages.list" :key="index" class="box-bubble" :id="`msg-${index}`"
				style="padding: 0 24rpx;">
				<view v-if="msg.type === 'TIMTextElem'" :class="['bubble', msg.flow]">
					<rich-text :nodes="msg.payload.text" />
				</view>

				<view v-if="msg.type === 'TIMImageElem'" :class="['bubble', msg.flow]">
					<image @click="previewImage([msg.payload.imageInfoArray[0].imageUrl])" style="width: 200rpx;" mode="widthFix"
						:src="msg.payload.imageInfoArray[0].imageUrl" />
				</view>

				<view v-if="msg.type === 'TIMVideoFileElem'" :class="['bubble', msg.flow]">
					<video style="width: 200rpx;" :src="msg.payload.videoUrl">
						<source :src="msg.payload.videoUrl" />
					</video>
				</view>
			</view>
		</scroll-view>
		<view class="footText">
			<input v-model="messages.currentMsg" class="foot-input" confirm-type="send" @confirm="send">
			<view @click="selectOptions" class="radio">
				<u-icon name="plus" color="#000" size="28" />
			</view>
		</view>
	</view>
</template>

<script>
import api from "@/config/api.js";
import storage from "@/utils/storage";
import { TYPES, EVENT } from "@/js_sdk/tim/tim-js";

let userID = "";
export default {
	data() {
		return {
			prescribingData: {},
			patientData: {},
			messages: {
				currentMsg: "",
				list: [],
				nextReqMessageID: ""
			}
		};
	},
	onUnload() {
		this.$tim.logout();
	},
	onLoad({ user_id }) {
		userID = user_id;
		// 选择的处方
		this.prescribingData = uni.getStorageSync("e-prescribingDetail");
		// 当前病人
		this.patientData = uni.getStorageSync("patientInfo");

		/**
			* 腾讯云 即时通讯IM
			*/
		uni.request({
			url: api.buyer + "/order/userConsult/createIMAccount",
			header: { "accessToken": storage.getAccessToken() },
			success: ({ data }) => {
				const { id: userID, userSig } = data.result
				this.$tim.login({ userID, userSig });
				this.$tim.on(EVENT.SDK_READY, this.getMessageList);
			}
		});

		this.$tim.on(EVENT.MESSAGE_RECEIVED, ({ data }) => {
			this.messages.list.push(...data);
		});
	},
	onPullDownRefresh() {
		this.getMessageList()
	},
	methods: {
		getMessageList() {
			uni.startPullDownRefresh();
			this.$tim.getMessageList({
				conversationID: `C2C${"1588437298660524032" || userID}`,
				nextReqMessageID: this.messages.nextReqMessageID
			}).then(({ data }) => {
				this.messages.list.unshift(...data.messageList);
				this.messages.nextReqMessageID = data.nextReqMessageID;
				uni.stopPullDownRefresh();
			});
		},
		selectOptions() {
			let message = null;
			uni.showActionSheet({
				itemList: ["图片", "视频"],
				success: async ({ tapIndex }) => {
					switch (tapIndex) {
						case 0: {
							const [, res] = await uni.chooseImage({ count: 1 });

							message = this.$tim.createImageMessage({
								to: "1588437298660524032" || userID,
								conversationType: TYPES.CONV_C2C,
								payload: { file: res },
								onProgress(event) { console.log('file uploading:', event) }
							});
						}
							break;
						case 1: {
							const [, res] = await uni.chooseVideo({ maxDuration: 60 });
							message = this.$tim.createVideoMessage({
								to: "1588437298660524032" || userID,
								conversationType: TYPES.CONV_C2C,
								payload: { file: res },
								onProgress(event) { console.log('file uploading:', event) }
							});
						}
							break;
						case 2:
							// iOS端无法选择系统文件
							break;
						default:
							break;
					}

					this.$tim.sendMessage(message).then(({ data }) => {
						this.messages.list.push(data.message);
					}).catch(imError => {
						// 发送失败
						console.warn('sendMessage error:', imError);
					});
				}
			});
		},
		previewImage(urls) {
			uni.previewImage({ urls });
		},
		send() {
			let message = this.$tim.createTextMessage({
				to: "1588437298660524032" || userID,
				conversationType: TYPES.CONV_C2C,
				payload: {
					text: this.messages.currentMsg
				},
			});

			this.$tim.sendMessage(message).then(({ data }) => {
				this.messages.list.push(data.message);
			}).catch((imError) => {
				console.warn('sendMessage error:', imError);
			});

			this.messages.currentMsg = "";
		}
	}
}
</script>


<style>
page {
	height: 100%;
}
</style>
<style lang="scss" scoped>
::v-deep.u-border-bottom {
	background-color: transparent !important;
}

.content {
	height: 100%;
	display: flex;
	justify-content: flex-start;
	flex-direction: column;
}

.message-list {
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
	flex: 1;
	overflow: hidden;
	padding: 30rpx;

	.box-bubble {
		display: flex;
		flex-direction: column;
	}
}

.prescription {
	position: fixed;
	left: 30rpx;
	bottom: 200rpx;
	padding: 0 30rpx;
	width: 32;
	height: 80rpx;
	color: #4c79e4;
	font-size: 30rpx;
	font-weight: bold;
	line-height: 80rpx;
	background-color: #fff;
	border-radius: 40rpx;
	text-align: center;
}

.bubble {
	display: flex;
	flex-direction: column;
	position: relative;
	border-radius: 12rpx;
	padding: 18rpx 30rpx;
	max-width: 100%;
	margin: 16rpx 0;
	border-radius: 12rpx;
	font-size: 26rpx;
	color: #333;


	&::before {
		content: " ";
		position: absolute;
		width: 0;
		height: 0;
		top: 50%;
		transform: translateY(-50%);
	}

	&.in {
		align-self: flex-start;
		background-color: #fff;

		&::before {
			border-top: 6px solid transparent;
			border-bottom: 6px solid transparent;
			border-right: 6px solid #fff;
			right: 100%;
		}
	}


	&.out {
		align-self: flex-end;
		background-color: #2f92d7;
		color: #fff;

		&::before {
			border-top: 6px solid transparent;
			border-bottom: 6px solid transparent;
			border-left: 6px solid #2f92d7;
			left: 100%;
		}
	}
}

.footText {
	// position: fixed;
	width: 100%;
	bottom: 20rpx;
	border-top: 1px solid #E3E3E3;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: 30rpx;

	.foot-input {
		width: 88%;
		height: 60rpx;
		padding: 0 24rpx;
		background: #ffffff;
		border-radius: 35rpx;
	}

	.radio {
		width: 49rpx;
		height: 49rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 24rpx;
		border: 4rpx solid #333333;
		border-radius: 50%;
		font-size: 40rpx;
		font-weight: bold;
	}
}
</style>
